package com.tyj.tuyijieapp.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.tyj.tuyijiecommon.aware.BeanUtil;
import com.tyj.tuyijiecommon.util.JwtUtil;
import com.tyj.tuyijiecommon.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 登陆成功处理器
 * </p>
 *
 * @author lhf
 * @since 2020/6/6
 */
public class SuccessHandler implements AuthenticationSuccessHandler {
    private static Logger log = LoggerFactory.getLogger(SuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.debug("登录成功处理器");
        response.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
//        JwtUtil jwtUtil = BeanUtil.getBean("jwtUtil", JwtUtil.class);
        UserDetails user = (UserDetails) authentication.getPrincipal();
        String token = JwtUtil.generate(user);
//        存到redis中
        RedisTemplate template = BeanUtil.getBean("redisTemplate", RedisTemplate.class);
        template.opsForValue().set("login:user:" + user.getUsername(), token, 30, TimeUnit.MINUTES);
        response.addHeader("Authentication", token);
        writer.write(JSONObject.toJSONString(Result.success()));
        writer.flush();
        writer.close();
    }
}
